const Layer = require("./layer");

function Route(path) {
  this.path = path;
  this.stack = [];
  this.methods = {};
}

Route.prototype.dispatch = function (req, res, done) {
  let idx = 0;
  const stack = this.stack;
  next();

  function next(err) {
    let layer = stack[idx++];
    if (!layer) return done(err);

    if (layer.method && layer.method !== req.method.toLowerCase()) {
      next(err);
    } else {
      if (err) {
        layer.handle_error(err, req, res, next);
      } else {
        layer.handle_request(req, res, next);
      }
    }
  }
};

Route.prototype.all = function (...args) {
  for (let fn of args) {
    const layer = new Layer("/", {}, fn);
    layer.method = undefined;
    this.methods._all = true;
    this.stack.push(layer);
  }

  return this;
};

Route.prototype.handle_method = function (method) {
  if (this.methods._all) return true;

  return this.methods[method.toLowerCase()];
};

Route.prototype.get = function (...args) {
  for (let fn of args) {
    const layer = new Layer("/", {}, fn);
    layer.method = "get";
    this.methods["get"] = true;
    this.stack.push(layer);
  }

  return this;
};

module.exports = Route;
